<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图书管理系统</title>
  <!-- 引入bootstrap.css -->
  <link rel="stylesheet" href="../../lib/bootstrap/dist/css/bootstrap.min.css">

</head>
<!-- 公共 -->
<link rel="stylesheet" href="../../css/base.css">
<link rel="stylesheet" href="./index.css">

</head>

<body>
  <div class="container">
    <div>
      <!-- 提示框 -->
      <div class="alert info-box">
        操作结果
      </div>
      <h3>欢迎登录图书管理系统</h3>
    </div>
    <!-- 表单 -->
    <div class="form_wrap" style="margin-top: 40px;">
      <form class="login-form">

        <div class="mb-3" style="display: flex; align-items: center;">
          <label class="form-label" style="margin-right: 25px;">用户名</label>
          <input type="text" name="username" class="form-control" style="flex:1">
        </div>
        <div class="mb-3" style="display: flex; align-items: center;">
          <label class="form-label" style="margin-right: 40px;">密码</label>
          <input type="password" name="password" class="form-control" style="flex:1" id="password">
        </div>

        <div style="margin-top: 20px;">
          <button type="button" class="btn btn-primary btn-login">登录</button>
          <button type="button" class="btn btn-primary btn-reg"> 注册</button>

        </div>
      </form>
    </div>
  </div>

</body>
<script src="../../lib/axios/dist/axios.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="../../lib/form-serialize.js"></script>
<script src="../../utils/alert.js"></script>
<script src="../../utils/request.js"></script>
<script>
  // 1.2 收集表单数据，注册点击事件，发送请求到后端
  document.querySelector('.btn-login').addEventListener('click', async () => {
    const form = document.querySelector('.login-form')
    // serialize 序列化表单数据
    const data = serialize(form, { hash: true, empty: true })
    // 判断表单内不是空
    if (data.username === '' || data.password === '') {
      myAlert(false, '请输入用户名或密码')
    } else {
      const res = await axios.post('/user/library/login', data)
      if (res.data.code === 1) {
        myAlert(true, '登录成功') 
        // 本地存储
        // 先移除之前的存储
        localStorage.removeItem('userId')
        localStorage.setItem('userId', res.data.data.userId)

        setTimeout(() => {
          location.href = '../main'
        }, 1000)
      } else {
        myAlert(false, res.data.msg)
      }
    }

  })

  // 跳转注册
  document.querySelector('.btn-reg').addEventListener('click', () => {
    location.href = '../reg/index.html'
  })

</script>

</html>